package com.quyunshuo.module.home.fragment.video

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.quyunshuo.androidbaseframemvvm.base.ktx.observeLiveData
import com.quyunshuo.androidbaseframemvvm.common.constant.KEY_ID
import com.quyunshuo.androidbaseframemvvm.common.constant.KEY_URL
import com.quyunshuo.androidbaseframemvvm.common.ui.BaseFragment
import com.quyunshuo.androidbaseframemvvm.common.utils.ToastUtil
import com.quyunshuo.androidbaseframemvvm.network.bean.ArticleBean
import com.quyunshuo.androidbaseframemvvm.network.bean.ArticleListRes2
import com.quyunshuo.module.home.activity.details.DetailsActivity
import com.quyunshuo.module.home.databinding.HomeFragmentVideo1Binding
import com.quyunshuo.module.home.databinding.HomeFragmentVideoBinding
import com.quyunshuo.module.home.fragment.CustomText
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author DBoy 2021/7/6 <p>
 * - 文件描述 : 测试fragment
 */
@AndroidEntryPoint
class VideoFragment1 : BaseFragment<HomeFragmentVideo1Binding, VideoViewModel>(),
    OnRefreshLoadMoreListener {
    private  val TAG = "VideoFragment"
    override val mViewModel by viewModels<VideoViewModel>()//与当前 Fragment 的生命周期绑定。
    override fun createVB() = HomeFragmentVideo1Binding.inflate(layoutInflater)
    private var mId: Int? = null

    private lateinit var adapter: ViedeoAdapter
    private val dataList = mutableListOf<ArticleBean>()
    private var page = 1
    private var isRefresh = true;//true是刷新 false是累加
    // 在 Fragment 中定义变量
    private var isFirstLoad = true
    companion object {
        fun newInstance(id: Int): VideoFragment1 {
            val args = Bundle()
            args.putInt(KEY_ID, id)
            val fragment = VideoFragment1()
            fragment.arguments = args
            Log.d("$id", "newInstance: $id")
            return fragment
        }
    }

    override fun HomeFragmentVideo1Binding.initView() {
        smartRefreshLayout?.apply {
            //autoRefresh() 在 initView 中直接调用 autoRefresh() 时，视图可能尚未完成测量或附加到窗口，导致刷新动画未触发。
            //ViewPager 默认会预加载相邻 Fragment，导致非当前页面的 Fragment 提前触发 autoRefresh()，但此时用户不可见，可能造成“刷新失效”的错觉。
            setEnableRefresh(true)
            setEnableLoadMore(true)
            setOnRefreshListener(this@VideoFragment1)
            setOnLoadMoreListener(this@VideoFragment1)
        }
        mId = arguments?.getInt(KEY_ID, 0)
        Log.d("$id", "newInstance:initview$mId$smartRefreshLayout")
        recyclerView.layoutManager = LinearLayoutManager(requireContext())
        adapter = ViedeoAdapter(dataList)
        adapter.onItemClickListener ={view,position->
            val intent = Intent(this@VideoFragment1.context, DetailsActivity::class.java)
            intent.putExtra(KEY_URL,dataList[position].link)
            startActivity(intent)
        }
        recyclerView.adapter = adapter

    }

    override fun onResume() {
        super.onResume()
        if (isVisible && isFirstLoad) {
            mBinding.smartRefreshLayout.autoRefresh()
            isFirstLoad = false // 标记为已加载
        }
    }
    private fun loadData() {
        mViewModel.getData(mId ?: 0, page)
    }

    override fun initObserve() {
        observeLiveData(mViewModel.firstData, ::videoDome)
    }

    private fun videoDome(articleListRes2: ArticleListRes2?) {
        val datas = articleListRes2?.getDatas()
        if (isRefresh) {
            dataList.clear()
            if (datas!!.isEmpty()) {
                ToastUtil.showToast("数据为空")
            }
            // 添加模拟数据
            articleListRes2?.getDatas()!!.forEach { dataList.add(it) }
            mBinding.smartRefreshLayout.finishRefresh()
        } else {
            if (datas!!.isEmpty()) {
                ToastUtil.showToast("数据已加载完毕")
            }
            articleListRes2?.getDatas()!!.forEach { dataList.add(it) }
            mBinding.smartRefreshLayout.finishLoadMore()

        }
        adapter.notifyDataSetChanged()
    }

    override fun initRequestData() {
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        page = 1
        isRefresh = true
        loadData()
        Log.d(TAG, "newInstance onRefresh: $mId")
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        page++
        isRefresh = false
        loadData()
    }
    override fun onDestroyView() {
        //在 onDestroyView 中重置刷新状态，防止因 Fragment 重用导致状态异常：
        mBinding.recyclerView.adapter = null
        Log.d(TAG, "onDestroyView: ")
        super.onDestroyView()
    }
}